package com.my.chapter15;

import java.lang.reflect.Constructor;

public class practice22 {
    public static void main(String[] args) {
        ClassAsFactory<Integer> fi =
                new ClassAsFactory<Integer>(Integer.class);
        Integer i = fi.create(6);
        if(i == null){
            System.out.println("Integer cannot be instantiated!");
        }else{
            System.out.println("Integer can be instantiated!");
        }
    }
}

class ClassAsFactory<T> {
    Class<T> kind;
    public ClassAsFactory(Class<T> kind) { this.kind = kind; }
    public T create(int arg) {
        try{
            for(Constructor<?> ctor : kind.getConstructors()) {
                Class<?>[] params = ctor.getParameterTypes();
                if(params.length == 1)
                    if(params[0] == int.class)
                        return kind.cast(ctor.newInstance(arg));
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }
        return null;
    }
}
